import { Link, useLocation } from "react-router-dom";
import style from './style.module.scss'
import { Avatar, Dropdown, type MenuProps } from "antd";
import { useEffect, useState } from "react";

export default function Nav() {
  const user = localStorage.getItem('user');
  const userData = user ? JSON.parse(user) : '';
  const src = userData?.src;
  const name = userData?.name;

  const location = useLocation();
  const [currentPath, setCurrentPath] = useState(location.pathname);

  useEffect(() => {
    setCurrentPath(location.pathname);
  }, [location.pathname]);  // 监听路由变化

  const navItems = [
    { path: "/", name: "门店总览" },
    { path: "/store", name: "单店信息" },
    { path: "/compare", name: "数据对比" },
    { path: "/management", name: "信息管理" }
  ];

  const handleLogout = () => {
    // 清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    // 重定向到登录页
    window.location.href = '/login';
  };

  const items: MenuProps['items'] = [{
    key: '1',
    label: (
      <a onClick={handleLogout}>退出</a>
    ),
  }]

  return (
    <div className={style.nav}>
      <h3>连锁餐饮可视化平台</h3>
      <div className={style.main}>
        {navItems.map(item => (
          <Link
            key={item.path}
            to={item.path}
            className={currentPath === item.path ? style.active : ''}
          >
            {item.name}
          </Link>
        ))}
      </div>
      <div className={style.user}>
        <Dropdown menu={{ items }}>
          <Avatar src={src} alt="" size={38} />
        </Dropdown>
        <span>{name}</span>
      </div>
    </div>

  )
}
